package jnpf.message.consumer;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.rabbitmq.client.Channel;
import jnpf.base.UserInfo;
import jnpf.base.util.SentMessageUtil;
import jnpf.message.entity.SendConfigTemplateEntity;
import jnpf.message.entity.SendMessageConfigEntity;
import jnpf.message.model.message.*;
import jnpf.message.service.SendConfigTemplateService;
import jnpf.message.service.SendMessageConfigService;
import jnpf.message.service.ThirdOpenService;
import jnpf.message.util.DataTypeEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Component
@Slf4j
@RequiredArgsConstructor
public class SynUserConsumer {
	public static final String FLOW_SYN_POSITION = "flow.syn.position";
	public static final String FLOW_SYN_ROLE = "flow.syn.role";
	public static final String FLOW_SYN_ORG = "flow.syn.org";
	public static final String FLOW_SYN_USER = "flow.syn.user";
	public static final String FLOW_SYN_BUSINESS_ROLE = "flow.syn.group";
	public static final String FLOW_SYN_ERROR = "flowSynError";

	private final ApplicationContext applicationContext;
	private final SentMessageUtil sentMessageUtil;
	private final SendMessageConfigService sendMessageConfigService;
	private final SendConfigTemplateService sendConfigTemplateService;

	@RabbitListener(queues = FLOW_SYN_USER, ackMode = "MANUAL")
	public void synUser(OpenUserModel message, Channel channel, Message amqpMessage) throws Exception {
		processMessage(message, DataTypeEnum.USER, channel, amqpMessage);
	}

	@RabbitListener(queues = FLOW_SYN_ORG, ackMode = "MANUAL")
	public void synOrg(OpenDeptModel message, Channel channel, Message amqpMessage) throws Exception {
		processMessage(message, DataTypeEnum.ORG, channel, amqpMessage);
	}

	@RabbitListener(queues = FLOW_SYN_ROLE, ackMode = "MANUAL")
	public void synRole(OpenRoleModel message, Channel channel, Message amqpMessage) throws Exception {
		processMessage(message, DataTypeEnum.ROLE, channel, amqpMessage);
	}

	@RabbitListener(queues = FLOW_SYN_POSITION, ackMode = "MANUAL")
	public void synPosition(OpenPositionModel message, Channel channel, Message amqpMessage) throws Exception {
		processMessage(message, DataTypeEnum.POSITION, channel, amqpMessage);
	}

	@RabbitListener(queues = FLOW_SYN_BUSINESS_ROLE, ackMode = "MANUAL")
	public void synGroup(OpenGroupModel message, Channel channel, Message amqpMessage) throws Exception {
		processMessage(message, DataTypeEnum.GROUP, channel, amqpMessage);
	}



	private void processMessage(OpenBaseModel message, DataTypeEnum dataTypeEnum, Channel channel, Message amqpMessage) throws Exception {
		log.info("[{}同步开始][消息内容({})]", dataTypeEnum.getDescription(), JSON.toJSONString(message));
		try {
			// 获取对应的业务服务
			ThirdOpenService thirdOpenService = (ThirdOpenService) applicationContext.getBean(dataTypeEnum.getServiceImpl());
			Object result = thirdOpenService.beforeProcess(message, null);
			if (ObjectUtil.isNotNull(result)) {
				thirdOpenService.afterProcess(ImmutableList.of(result));
			}

			// 手动确认消息
			channel.basicAck(amqpMessage.getMessageProperties().getDeliveryTag(), false);
			log.info("[{}同步结束][处理结果({})]", dataTypeEnum.getDescription(), JSON.toJSONString(result));
		} catch (Exception e) {
			log.error("[{}同步失败][错误信息: {}]", dataTypeEnum.getDescription(), e.getMessage(), e);
			//推送企业微信
			SendMessageConfigEntity configEntity = sendMessageConfigService.getInfoByEnCode(FLOW_SYN_ERROR);
			if (Objects.nonNull(configEntity)) {
				List<SendConfigTemplateEntity> configTemplateEntityList = sendConfigTemplateService.getDetailListByParentId(configEntity.getId());
				SendConfigTemplateEntity entity = configTemplateEntityList.get(0);
				Map<String, Object> paramMap = ImmutableMap.of(entity.getId() + "@Title", "同步" + dataTypeEnum.getDescription() + "信息错误",
						entity.getId() + "@SendTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")),
						entity.getId() + "mqMessage", JSON.toJSONString(message),
						entity.getId() + "errorType", dataTypeEnum.getDescription(),
						entity.getId() + "message", e.getMessage());
				sentMessageUtil.SendWebHook(null, new UserInfo(), entity, paramMap, new HashMap<>());
			}
		}
	}


}
